

package com.asisto.controller


import com.asisto.model.*

class ClienteController {

    def authenticateService
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        [ clienteInstanceList: Cliente.list( params ), clienteInstanceTotal: Cliente.count() ]
    }

    def show = {
        def clienteInstance = Cliente.get( params.id )

        if(!clienteInstance) {
            flash.message = "Cliente not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ clienteInstance : clienteInstance ] }
    }

    def delete = {
        def clienteInstance = Cliente.get( params.id )
        if(clienteInstance) {
            try {
                clienteInstance.delete(flush:true)
                flash.message = "Cliente ${params.id} deleted"
                redirect(action:list)
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "Cliente ${params.id} could not be deleted"
                redirect(action:show,id:params.id)
            }
        }
        else {
            flash.message = "Cliente not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def clienteInstance = Cliente.get( params.id )


        log.info "cliente con id ${params.id}..."

        if(!clienteInstance) {
            flash.message = "Cliente not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            //Obtiene las notas del cliente
            def notas = NotaCliente.findAllByCliente(clienteInstance)

            return [ clienteInstance : clienteInstance, notasCliente: notas ]
        }
    }


    def nuevaNota = {

        def notas = [] 
        def mensaje = params.mensaje
        def idCliente = params.cliente

        log.info "Crea una nueva nota para el cliente con id $idCliente"

        User usuario = authenticateService.userDomain()

        def nombreUsuario = usuario ? usuario.userRealName : 'desconocido'

        log.info "Con el usuario $nombreUsuario"


        if (idCliente) {
            Cliente cliente = Cliente.get(idCliente)

            log.info "Cliente : $cliente"

            if (cliente) {
                NotaCliente nota = new NotaCliente(cliente:cliente
                    , mensaje:mensaje, usuario: nombreUsuario)
                cliente.addToNotas(nota)

                nota.save(flush:true)
                cliente.save()

                //Obtiene las notas del cliente
                notas = NotaCliente.findAllByCliente(cliente)

            }

        }

        

        render(template:'/cliente/listaNotas', model:['notas':notas])
        
    }

    def update = {
        def clienteInstance = Cliente.get( params.id )
        if(clienteInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(clienteInstance.version > version) {
                    
                    clienteInstance.errors.rejectValue("version", "cliente.optimistic.locking.failure", "Another user has updated this Cliente while you were editing.")
                    render(view:'edit',model:[clienteInstance:clienteInstance])
                    return
                }
            }
            clienteInstance.properties = params
            if(!clienteInstance.hasErrors() && clienteInstance.save()) {
                flash.message = "Cliente ${params.id} updated"
                redirect(action:show,id:clienteInstance.id)
            }
            else {
                render(view:'edit',model:[clienteInstance:clienteInstance])
            }
        }
        else {
            flash.message = "Cliente not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def create = {
        def clienteInstance = new Cliente()
        clienteInstance.properties = params
        return ['clienteInstance':clienteInstance]
    }

    def save = {
        def clienteInstance = new Cliente(params)
        if(!clienteInstance.hasErrors() && clienteInstance.save()) {
            flash.message = "Cliente ${clienteInstance.id} created"
            redirect(action:show,id:clienteInstance.id)
        }
        else {
            render(view:'create',model:[clienteInstance:clienteInstance])
        }
    }
}
